import { Ref } from "vue-demi"
import { ElMessage } from "element-plus"
import { ElFormType, FormDataType } from "../type"
import { UserState } from "@/store/modules/user"
import http from "@/utils/http"
import { useRouter } from "vue-router"
import { useStore } from "@/store/index"
interface params {
  formData: FormDataType
  formRef: Ref<ElFormType>
  btnLoading: Ref<boolean>
}
function useSubmit({ formData, formRef, btnLoading }: params) {
  const router = useRouter()
  const store = useStore()
  const submit = () => {
    formRef.value.validate(async (valid: boolean | undefined) => {
      if (valid) {
        if (formData.password !== formData.confirmPassword) {
          ElMessage.error("两次输入密码不同")
          return
        }
        btnLoading.value = true
        const res = await http.post<{ user: UserState; token: string }>(
          "/user/register",
          formData
        )
        btnLoading.value = false
        if (res.code === 1) {
          ElMessage.success("注册成功")
          store.commit("user/setUser", res.data?.user)
          sessionStorage.setItem("token", res.data?.token as string)
          router.push("/")
        } else {
          ElMessage.error(res.msg)
        }
      }
    })
  }
  return { submit }
}
export default useSubmit
